//
//  TJTransferController.m
//  Teleport
//
//  Created by xtjun on 2020/6/13.
//  Copyright © 2020 xtjun. All rights reserved.
//转账

#import "TJTransferController.h"
#import "TJScanController.h"
#import "TJSettingMoneyPasswordController.h"
#import "TJCoinNameListController.h"
#import "TJBuySellNeedAuthController.h"
#import "TJTransferRecordListController.h"
@interface TJTransferController ()<UITextFieldDelegate>

//@property (copy, nonatomic) NSString *coinNo;

@property (weak, nonatomic) UITextField *numberTextField;
@property (weak, nonatomic) UITextField *userIdTextField;
@property (weak, nonatomic) UITextField *passwordTextField;
@property (weak, nonatomic) UILabel *freeValueLabel;
//@property (copy, nonatomic) NSString *ishasTradePassword;
@property (weak, nonatomic) UIView *freeContentView;
//@property (weak, nonatomic) UIView *passwordContentView;
@property (weak, nonatomic) UIButton *coinNameButton;
@property (weak, nonatomic) UIButton *determineButton;

//@property (strong, nonatomic) NSDictionary *authDict;

/**费率 */
@property (assign, nonatomic) double roat;
/**最小数量 */
@property (assign, nonatomic) double minNum;

/**转账token */
@property (copy, nonatomic)  NSString *changeToken;
@end

@implementation TJTransferController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationBar.title = @"转账".localizedString;
    
    self.navigationBar.rightBarButton = [TJButtonBarButton barButtonWithTitle:@"转账记录".localizedString target:self action:@selector(didClickNavbarRightButton)];
    
    self.view.backgroundColor = UIColor_Hex(0xf2f2f2);
    
    
    UILabel *titleLabel = [UILabel lableWithSuperView:self.view font:MediumFont(15) color:UIColor_Hex(0x333333) title:@"转账".localizedString textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.offset(16);
        make.height.offset(40);
    }];
    
    UIView *speciesContentView = [UIView tj_addToView:self.view];
    speciesContentView.backgroundColor = UIColor.whiteColor;
    [speciesContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(titleLabel.mas_bottom);
        make.height.offset(44);
    }];
    
    
    UILabel *speciesLabel = [UILabel lableWithSuperView:speciesContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"转账种类".localizedString textAlignment:NSTextAlignmentLeft];
    [speciesLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(12);
    }];
    
    [speciesLabel setContentHuggingPriority:(UILayoutPriorityRequired) forAxis:(UILayoutConstraintAxisHorizontal)];
    

    UIButton *coinNameButton = [UIButton buttonWithSuperView:speciesContentView font:UIFont_Px(12) color:UIColor_Hex(0x666666) title:@"BTC"];
    [coinNameButton setImage:[UIImage imageNamed:@"cellArrowIcon"] forState:UIControlStateNormal];
    [coinNameButton setImage:[UIImage imageNamed:@"cellArrowIcon"] forState:UIControlStateHighlighted];
    [coinNameButton addTarget:self action:@selector(didClickCoinNameButton) forControlEvents:UIControlEventTouchUpInside];
    [coinNameButton setImagePosition:LXMImagePositionRight spacing:3];
    [coinNameButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [coinNameButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(80);
        make.right.offset(-12);
        make.height.offset(30);
        make.centerY.offset(0);
    }];
    
    
    UIView *accountContentView = [UIView tj_addToView:self.view];
    accountContentView.backgroundColor = UIColor.whiteColor;
    [accountContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(speciesContentView.mas_bottom).offset(10);
        make.height.offset(44);
    }];
    
    UILabel *accountLabel = [UILabel lableWithSuperView:accountContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"收款账户".localizedString textAlignment:NSTextAlignmentLeft];
    CGFloat accountLabelW = [accountLabel.text getStringSizeWithWidth:200 font:accountLabel.font].width + 5;
    [accountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(12);
        make.height.offset(accountLabelW);
        make.height.offset(40);
    }];
    
    
    UIView *accountLineView = [UIView tj_addToView:accountContentView];
    accountLineView.backgroundColor = UIColor.tj_separatorColor;
    [accountLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.bottom.offset(0);
        make.height.offset(1);
    }];
    
    
    UITextField *userIdTextField = [UITextField tj_addToView:accountContentView];
    userIdTextField.placeholder = @"请输入用户UID".localizedString;
    userIdTextField.font = UIFont_Px(15);
    [userIdTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    userIdTextField.keyboardType = UIKeyboardTypeNumberPad;
    [userIdTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(accountLabel.mas_right).offset(30);
        make.centerY.offset(0);
        make.height.offset(34);
        make.right.offset(-60);
    }];
    userIdTextField.text = self.UID;
    [accountLabel setContentHuggingPriority:(UILayoutPriorityRequired) forAxis:(UILayoutConstraintAxisHorizontal)];
    [userIdTextField setContentHuggingPriority:(UILayoutPriorityDefaultLow) forAxis:(UILayoutConstraintAxisHorizontal)];
    
    UIButton *scanButton = [UIButton tj_addToView:accountContentView];
    [scanButton setImage:[UIImage imageNamed:@"small_scan_icon"] forState:UIControlStateNormal];
    [scanButton setImage:[UIImage imageNamed:@"small_scan_icon"] forState:UIControlStateHighlighted];
    [scanButton addTarget:self action:@selector(didClickScanButton) forControlEvents:UIControlEventTouchUpInside];
    [scanButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [scanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(30);
        make.right.offset(-16);
        make.height.offset(30);
        make.centerY.offset(0);
    }];
    
    UIView *userIDLineView = [UIView tj_addToView:accountContentView];
    userIDLineView.backgroundColor = UIColor.tj_separatorColor;
    [userIDLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.bottom.offset(0);
        make.height.offset(1);
    }];
    
    
    UIView *numberContentView = [UIView tj_addToView:self.view];
    numberContentView.backgroundColor = UIColor.whiteColor;
    [numberContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(accountContentView.mas_bottom);
        make.height.offset(44);
    }];
    
    UILabel *numberLabel = [UILabel lableWithSuperView:numberContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"转账数量".localizedString textAlignment:NSTextAlignmentLeft];
    CGFloat numberLabelW = [numberLabel.text getStringSizeWithWidth:200 font:numberLabel.font].width + 5;
    [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(12);
        make.height.offset(40);
        make.width.offset(numberLabelW);
    }];
    
    
    UITextField *numberTextField = [UITextField tj_addToView:numberContentView];
    numberTextField.placeholder = @"请输入转账数量".localizedString;
    numberTextField.font = UIFont_Px(15);
    [numberTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    numberTextField.keyboardType = UIKeyboardTypeDecimalPad;
    [numberTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(numberLabel.mas_right).offset(25);
        make.centerY.offset(0);
        make.height.offset(34);
        make.right.offset(-60);
    }];
    numberTextField.delegate  = self;
    
    [numberLabel setContentHuggingPriority:(UILayoutPriorityRequired) forAxis:(UILayoutConstraintAxisHorizontal)];
    [numberTextField setContentHuggingPriority:(UILayoutPriorityDefaultLow) forAxis:(UILayoutConstraintAxisHorizontal)];
    
    UIView *numberLineView = [UIView tj_addToView:numberContentView];
    numberLineView.backgroundColor = UIColor.tj_separatorColor;
    [numberLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.bottom.offset(0);
        make.height.offset(1);
    }];
    
    
    UIView *freeContentView = [UIView tj_addToView:self.view];
    freeContentView.backgroundColor = UIColor.whiteColor;
    [freeContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(numberContentView.mas_bottom);
        make.height.offset(44);
    }];
    
    UILabel *freeLabel = [UILabel lableWithSuperView:freeContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"手续费".localizedString textAlignment:NSTextAlignmentLeft];
    [freeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(12);
    }];
    
    UILabel *freeValueLabel = [UILabel lableWithSuperView:freeContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"" textAlignment:NSTextAlignmentLeft];
    [freeValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(-12);
    }];
    
    UIButton *determineButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(18) color:UIColor.whiteColor title:@"确定".localizedString];
    determineButton.backgroundColor = UIColor_Hex(0x2C6CC7);
    [determineButton shearRoundedCornersWithRadiu:22];
    [determineButton addTarget:self action:@selector(didClickDetermineButton) forControlEvents:UIControlEventTouchUpInside];
    [determineButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(numberContentView);
        make.left.equalTo(numberContentView);
        make.height.offset(44);
        make.bottom.offset(-TabbarSafeBottomMargin - 64);
    }];
    
    _freeValueLabel = freeValueLabel;
    _numberTextField = numberTextField;
    _userIdTextField = userIdTextField;
    _freeContentView = freeContentView;
    _coinNameButton = coinNameButton;
    _determineButton = determineButton;
    
    
    [self textFieldDidChange:userIdTextField];
    
    [self setIshasTradePassword];
    /**获取转账配置 */
    [self loadChangeData];
}

- (void)setIshasTradePassword {
        
        UIView *passwordContentView = [UIView tj_addToView:self.view];
        passwordContentView.backgroundColor = UIColor.whiteColor;
        [passwordContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(16);
            make.right.offset(-16);
            make.top.equalTo(self.freeContentView.mas_bottom).offset(10);
            make.height.offset(44);
        }];
        
        UILabel *passwordLabel = [UILabel lableWithSuperView:passwordContentView font:UIFont_Px(15) color:UIColor_Hex(0x262626) title:@"交易密码".localizedString textAlignment:NSTextAlignmentLeft];
        [passwordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.left.offset(12);
        }];
        
        UITextField *passwordTextField = [UITextField tj_addToView:passwordContentView];
        passwordTextField.placeholder = @"请输入交易密码".localizedString;
        passwordTextField.font = UIFont_Px(15);
        passwordTextField.secureTextEntry = YES;
        passwordTextField.keyboardType = UIKeyboardTypeNumberPad;
        [passwordTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        [passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(passwordLabel.mas_right).offset(30);
            make.centerY.offset(0);
            make.height.offset(34);
            make.right.offset(-60);
        }];
        
        [passwordLabel setContentCompressionResistancePriority:(UILayoutPriorityRequired) forAxis:UILayoutConstraintAxisHorizontal];
        _passwordTextField = passwordTextField;
   
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    
    if (textField == _numberTextField) {//计算手续费
        double roatDoubl = [textField.text doubleValue] * self.roat;
        NSString *moneyStr = [NSString stringWithFormat:@"%f",roatDoubl];
        self.freeValueLabel.text = [Tools CNYString:moneyStr];
        
        //提示最小转币数量
       
        if ([textField.text doubleValue] < self.minNum) {
            NSString * minNumStr = [NSString stringWithFormat:@"最小转账数量为%@",@(self.minNum).stringValue];
            [TJHud showTopAutoHideMessage:minNumStr];
            
        }
    }
    
    if (textField == _userIdTextField) {//获取token
        if (textField.text.length == 8) {
            /**获取转账token */
            [self loadTokenData];
        }
    }
    
    _determineButton.userInteractionEnabled = _numberTextField.text.length && _userIdTextField.text.length && _passwordTextField.text.length;
    _determineButton.backgroundColor = (_determineButton.userInteractionEnabled) ? UIColor.tj_mainColor : [UIColor_Hex(0x666666) colorWithAlphaComponent:0.3];
    
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(nonnull NSString *)string {
    
    if (textField == self.numberTextField) {
        // 限制第一位不能是小数点
        if(textField.text.length == 0 && [string isEqualToString:@"."])return NO;
        //第一位不为零
//        if(textField.text.length == 0 && [string isEqualToString:@"0"])return NO;
        
    }
    
    return  YES;
    
}


- (void)transfer {
    
    NSString *password = _passwordTextField.text;
    NSString *number = _numberTextField.text;
    NSString *uuid = _userIdTextField.text;
  
    if ([_numberTextField.text doubleValue] < self.minNum) {
              NSString * minNumStr = [NSString stringWithFormat:@"最小转账数量为%@",@(self.minNum).stringValue];
              [TJHud showTopAutoHideMessage:minNumStr];
        
        return;
              
          }
    
    
    NSDictionary *parameters = @{
        @"pwd": password,
        @"uuid": uuid,
        @"currency": _coinNameButton.titleLabel.text,
        @"num": number,
        @"userId": TJUserInfo.readInfo.userId,
        @"tokenId": self.changeToken ?: @""
    };
    
    [self showloading];
    
    [TJNetworking.shareNetworking POSTNew:@"member/transfer" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        [self hiddenloading];
        
        [TJHud showAutoHideMessage:@"转账成功".localizedString];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
        
    } failure:^(NSError * _Nonnull error) {
        [self hiddenloading];
        self.userIdTextField.text = nil;
        [self textFieldDidChange:self.userIdTextField];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
    
}

- (void)didClickDetermineButton {
    
    weakify(self)
    [TJNetworking.shareNetworking updateUserInfoAndLoading:YES success:^(TJUserInfo * _Nonnull userInfo) {
        
        if (userInfo.bankCard.replacingEmptyString.length &&  userInfo.cardNo.replacingEmptyString.length) {
            //发起转账
            [weakself transfer];
            
        }else{
            TJBuySellNeedAuthController *buySellNeedAuthController = [[TJBuySellNeedAuthController alloc] init];
            buySellNeedAuthController.title = @"转账需要完成以下认证：".localizedString;
            [weakself presentViewController:buySellNeedAuthController animated:NO completion:nil];
        }
    }];
}


- (void)didClickScanButton {
    weakify(self)
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                TJScanController *scanController = [[TJScanController alloc] init];
                [scanController setScanComplete:^(NSString * _Nonnull result) {
                    [TJQrcodeResultHandler QrCodeResultHandlerWithController:self result:result isNeedHandle:NO complete:^(NSDictionary * _Nonnull dict) {
                        weakself.userIdTextField.text = dict[@"uuid"];
                        [weakself textFieldDidChange:weakself.userIdTextField];
                    }];
                }];
                [self presentViewController:scanController animated:YES completion:nil];
            }
        });
    }];
    
    AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        [self alertWithTitle:nil message:@"不能使用相机,前往开启？".localizedString leftButtonName:@"取消".localizedString rightButtonName:@"前往开启".localizedString leftButtonBlock:nil rightButtonBlock:^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }];
        return;
    }
}

/**币种选择 */
- (void)didClickCoinNameButton {
    TJCoinNameListController *coinNameListController = [[TJCoinNameListController alloc] init];
    [coinNameListController setComplete:^(NSString * _Nonnull coinName, NSString * _Nonnull coinNo) {
        [self.coinNameButton setTitle:coinName forState:UIControlStateNormal];
       
        [self.coinNameButton setImagePosition:LXMImagePositionRight spacing:3];
        
        /**获取转账配置 */
            [self loadChangeData];
               
      
    }];
    [self.navigationController pushViewController:coinNameListController animated:YES];
}

- (void)didClickNavbarRightButton {
    TJTransferRecordListController *vc = [TJTransferRecordListController new];
    
    [self.navigationController pushViewController:vc animated:YES];
}

/**获取转账配置 */
-(void)loadChangeData {
    //清空数量
    self.numberTextField.text = nil;
    [self textFieldDidChange:self.numberTextField];
    
    
    //获取用户信息
    [self showloading];
    [TJNetworking.shareNetworking GET:@"member/transfer" parameters:@{@"currency": _coinNameButton.titleLabel.text} success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
        [self hiddenloading];
        self.roat = [data[@"roat"] doubleValue];
        self.minNum = [data[@"minNum"] doubleValue];
    } failure:^(NSError * _Nonnull error) {
        [self hiddenloading];
         [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}

/**获取转账token */
-(void)loadTokenData {
  
    //获取用户信息
  [self showloading];
    [TJNetworking.shareNetworking POSTNew:@"member/transfer/getAuth" parameters:@{@"userId": TJUserInfo.readInfo.userId} success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
         [self hiddenloading];
        self.changeToken = data;
      
    } failure:^(NSError * _Nonnull error) {
         [self hiddenloading];
       [TJHud showAutoHideMessage:error.localizedFailureReason];
        
    }];
}
@end
